//
//  DualMediationMAXSplashManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DualMediationMAXSplashManager.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../Utils/JSON/DMConfigReader.h"
#import "../../API/AdStrategy/IMAdStrategyManager.h"
#import "../../API/AdStrategy/IMAdStrategyModels.h"
#import "DMAdDelegate.h"
#import "DMThinkingManager.h"
#import <AdjustSdk/AdjustSdk.h>

#import <FirebaseAnalytics/FirebaseAnalytics.h>
#if __has_include(<AppLovinSDK/AppLovinSDK.h>)
#import <AppLovinSDK/AppLovinSDK.h>
#define APPLOVIN_SDK_AVAILABLE 1
#else
#define APPLOVIN_SDK_AVAILABLE 0
#endif

// 定义开屏广告时间常量
#define SPLASH_AD_DURATION 3.0
#define MAXSPLASH_Ad_UnitID @"0543d10a854014ec"

#if APPLOVIN_SDK_AVAILABLE
@interface DualMediationMAXSplashManager () <MAAdDelegate, MAAdRevenueDelegate>
@property (nonatomic, strong) MAAppOpenAd *splashAd;
#else
@interface DualMediationMAXSplashManager ()
#endif
@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, assign) NSInteger retryAttempt;
@property (nonatomic, assign) BOOL isSplashDisabled;
@property (nonatomic, assign) BOOL isUserClicked;
@property (nonatomic, assign) BOOL isUserClosed;
@property (nonatomic, assign) BOOL isSplashAdReady;
@property (nonatomic, strong) NSString *currentScene;
@property (nonatomic, strong) NSString *currentAdId;

@end

@implementation DualMediationMAXSplashManager

- (instancetype)init {
    self = [super init];
    if (self) {
        // 自定义初始化逻辑
        self.isSplashDisabled = YES;
        self.isUserClosed = NO;
        self.isSplashAdReady = NO;
    }
    return self;
}

static DualMediationMAXSplashManager *_splash = nil;
+ (instancetype)sharedSplashManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _splash = [[self alloc] init];
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 初始化 WDSplashManager 单例"];
    });
    return _splash;
}

- (void)setSplashAdDisable:(BOOL)isDisable {
    [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 设置开屏广告禁用状态: %@", isDisable ? @"禁用" : @"启用"];
    self.isSplashDisabled = isDisable;
}

- (void)initSplashDelegate {
    [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 开始设置代理和初始化开屏广告"];
    // 初始化开屏广告
#if APPLOVIN_SDK_AVAILABLE
    NSString *adUnit = MAXSPLASH_Ad_UnitID;
    if (adUnit.length > 4) {
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 加载广告位 ID: %@", adUnit];
        self.splashAd = [[MAAppOpenAd alloc] initWithAdUnitIdentifier:adUnit];
        self.splashAd.delegate = self;
        self.splashAd.revenueDelegate = self;
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] splashAd 初始化完成，开始加载广告"];
        
        // 初始化时根据广告策略预加载开屏广告（ad_status + 条件）
        IMAdScene scene = [self determineSplashScene];
        IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
        if (![strategyManager isAdEnabledForScene:scene]) {
            [IMLogUtils warning:IMLogTagAd format:@"[MAX Splash] 当前场景广告被策略(ad_status=0)禁用，跳过预加载"];
        } else if (![self shouldShowSplashBasedOnConfig]) {
            [IMLogUtils warning:IMLogTagAd format:@"[MAX Splash] 按策略条件判断不应加载/展示开屏广告，跳过预加载"];
        } else {
            [self loadSplash];
        }
    } else {
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 无效广告位，跳过初始化"];
    }
#else
    [IMLogUtils warning:IMLogTagAd format:@"[MAX Splash] AppLovin SDK 不可用，跳过初始化"];
#endif
}

- (NSString *)getCurrentSplashScene {
    IMAdScene scene = [self determineSplashScene];
    if (scene == IMAdSceneSplashCool) {
        return @"SCENE_SPLASH_COOL";
    } else {
        return @"SCENE_SPLASH_HOT";
    }
}

- (BOOL)isSplashAdReady {
#if APPLOVIN_SDK_AVAILABLE
    return [self.splashAd isReady];
#else
    return NO;
#endif
}

- (BOOL)shouldShowSplashBasedOnConfig {
    // 判断应用启动状态（冷启动或热启动）
    IMAdScene splashScene = [self determineSplashScene];
    
    // 使用IMAdStrategyManager获取开屏广告策略
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    
    __block BOOL shouldShow = NO;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [strategyManager reportLevelBehavior:splashScene
                                   level:1
                              onlineTime:0
                              completion:^(BOOL shouldShowAd, id _Nullable condition) {
        shouldShow = shouldShowAd;
        
        if (condition) {
            NSDictionary *conditionDict = (NSDictionary *)condition;
            NSString *sceneType = (splashScene == IMAdSceneSplashCool) ? @"冷启动" : @"热启动";
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] %@开屏广告策略配置:", sceneType];
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] - 启动次数要求: %ld", (long)[conditionDict[@"launch_times"] integerValue]];
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] - 广告天间隔: %ld", (long)[conditionDict[@"ad_day_interval"] integerValue]];
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] - 广告次数间隔: %ld", (long)[conditionDict[@"ad_times_interval"] integerValue]];
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] - 每日广告上限: %ld", (long)[conditionDict[@"ad_daily_limit"] integerValue]];
            [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] - 广告等待时间: %ld秒", (long)[conditionDict[@"ad_wait_time"] integerValue]];
        }
        
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 广告策略结果: %@", shouldShowAd ? @"展示" : @"不展示"];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    // 等待策略结果
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return shouldShow;
}

/**
 * 判断应用启动状态，返回相应的开屏广告场景
 * @return 冷启动或热启动场景
 */
- (IMAdScene)determineSplashScene {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *lastActiveDate = [defaults objectForKey:@"WDLastActiveDate"];
    NSDate *currentDate = [NSDate date];
    
    // 更新最后活跃时间
    [defaults setObject:currentDate forKey:@"WDLastActiveDate"];
    [defaults synchronize];
    
    if (!lastActiveDate) {
        // 首次启动，视为冷启动
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 首次启动，使用冷启动策略"];
        return IMAdSceneSplashCool;
    }
    
    // 计算时间间隔（秒）
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:lastActiveDate];
    
    // 如果超过30分钟（1800秒）未活跃，视为冷启动
    if (timeInterval > 1800) {
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 应用已超过30分钟未活跃（%.0f秒），使用冷启动策略", timeInterval];
        return IMAdSceneSplashCool;
    } else {
        [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 应用在30分钟内活跃过（%.0f秒前），使用热启动策略", timeInterval];
        return IMAdSceneSplashHot;
    }
}

#if UIKIT_AVAILABLE
/**
 * 获取父视图控制器
 */
- (UIViewController *)getParentViewController {
    UIWindow *keyWindow = nil;
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if ([scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        keyWindow = window;
                        break;
                    }
                }
                if (keyWindow) break;
            }
        }
    } else {
        keyWindow = [UIApplication sharedApplication].keyWindow;
    }
    
    return keyWindow.rootViewController;
}
#endif

- (void)showSplash {
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] ========== 开始展示开屏广告 =========="];
    
    if (self.isUserClosed) {
        [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] 用户已主动关闭，不展示广告"];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowSplashAdForScene:error:)]) {
            NSString *scene = [self getCurrentSplashScene];
            NSError *error = [NSError errorWithDomain:@"DualMediationMAXSplash" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"用户已关闭"}];
            [self.delegate dmAdManager:self didFailToShowSplashAdForScene:scene error:error];
        }
        return;
    }
    
    // 策略：广告是否启用（ad_status）
    IMAdScene sceneEnum = [self determineSplashScene];
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    if (![strategyManager isAdEnabledForScene:sceneEnum]) {
        [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] 场景广告被策略(ad_status=0)禁用，不展示/加载"];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowSplashAdForScene:error:)]) {
            NSString *scene = [self getCurrentSplashScene];
            NSError *error = [NSError errorWithDomain:@"DualMediationMAXSplash" code:1002 userInfo:@{NSLocalizedDescriptionKey: @"策略禁用(ad_status=0)"}];
            [self.delegate dmAdManager:self didFailToShowSplashAdForScene:scene error:error];
        }
        return;
    }
    
    // 策略：是否应展示（频控等条件）
    if (![self shouldShowSplashBasedOnConfig]) {
        [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 按策略条件判断不应展示开屏广告"];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowSplashAdForScene:error:)]) {
            NSString *scene = [self getCurrentSplashScene];
            NSError *error = [NSError errorWithDomain:@"DualMediationMAXSplash" code:1003 userInfo:@{NSLocalizedDescriptionKey: @"策略条件不满足"}];
            [self.delegate dmAdManager:self didFailToShowSplashAdForScene:scene error:error];
        }
        return;
    }
    
    // 确定开屏场景
    NSString *splashScene = [self getCurrentSplashScene];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 开屏场景: %@", splashScene];
    
    // 埋点：展示请求
    NSDictionary *showRequestParams = @{
        @"w_platform": @"MAX",
        @"w_ad_scene": splashScene,
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": MAXSPLASH_Ad_UnitID
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
    
    [self loadSplash];
}

- (void)loadSplash {
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 开始加载开屏广告"];
    
    if (self.isUserClosed) {
        [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] 用户已关闭，跳过加载"];
        return;
    }
    
    // 在加载前再次检查策略开关与策略条件
    IMAdScene sceneEnum = [self determineSplashScene];
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    if (![strategyManager isAdEnabledForScene:sceneEnum]) {
        [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] 场景广告被策略(ad_status=0)禁用，跳过加载"];
        return;
    }
    if (![self shouldShowSplashBasedOnConfig]) {
        [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 按策略条件判断不应加载开屏广告，跳过加载"];
        return;
    }
    
    // 埋点：填充请求
    NSDictionary *fillRequestParams = @{
        @"w_platform": @"MAX",
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": MAXSPLASH_Ad_UnitID
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    
#if APPLOVIN_SDK_AVAILABLE
    [self.splashAd loadAd];
#else
    [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] AppLovin SDK 不可用，无法加载"];
#endif
}

#if APPLOVIN_SDK_AVAILABLE
- (void)didLoadAd:(MAAd *)ad {
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] ✅ 开屏广告加载成功"];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 广告信息: %@", ad];
    
    self.isSplashAdReady = YES;
    
    // 埋点：填充成功
    NSDictionary *fillSuccessParams = @{
        @"w_platform": @"MAX",
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @""
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
    
    // 立即展示
#if UIKIT_AVAILABLE
    UIViewController *parentVC = [self getParentViewController];
    if (parentVC) {
        [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 开始展示开屏广告"];
        [self.splashAd showAd];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"💦 [MAX Splash] 无法获取父视图控制器"];
    }
#endif
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error
{
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] ❌ 开屏广告加载失败"];
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] 错误代码: %ld", (long)error.code];
    
    self.isSplashAdReady = NO;
    
    // 埋点：填充失败
    NSDictionary *fillFailParams = @{
        @"w_platform": @"MAX",
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": adUnitIdentifier ?: @"",
        @"w_error_code": @(error.code),
        @"w_error_msg": error.message ?: @"加载失败"
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
    
    NSString *scene = [self getCurrentSplashScene];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowSplashAdForScene:error:)]) {
        NSError *nsError = [NSError errorWithDomain:@"DualMediationMAXSplash" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"加载失败"}];
        [self.delegate dmAdManager:self didFailToShowSplashAdForScene:scene error:nsError];
    }
}

- (void)didDisplayAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 👁️ 开屏广告开始展示"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    NSString *scene = [self getCurrentSplashScene];
    
    // 埋点：展示成功
    NSDictionary *showSuccessParams = @{
        @"w_platform": @"MAX",
        @"w_ad_scene": scene,
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
    
    // 埋点：展示完成（开屏广告显示即完成）
    NSDictionary *showCompletedParams = @{
        @"w_platform": @"MAX",
        @"w_ad_scene": scene,
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:showCompletedParams];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 事件打点: SDK_ad_show_completed"];
    // 新增 AD_Splash_show 埋点
    @try {
        double ecpm = ad.revenue * 1000.0;
        NSDictionary *splashShowParams = @{
            @"w_scene": scene ?: @"default",
            @"w_revenue": @(ecpm),
            @"w_auctionId":[DMConfigReader auctionId]
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Splash_show" jsonStr:splashShowParams];
        
        ADJAdRevenue *adj = [[ADJAdRevenue alloc] initWithSource:@"applovin_max_sdk"];
        [adj setRevenue:ad.revenue currency:@"USD"];
        [adj setAdRevenueNetwork:ad.networkName];
        [adj setAdRevenueUnit:ad.adUnitIdentifier];
        [adj setAdRevenuePlacement:ad.placement];
        [adj addPartnerParameter:@"ad_format" value:ad.format.label];
        [adj addPartnerParameter:@"ad_unit_id" value:ad.adUnitIdentifier];
        [Adjust trackAdRevenue:adj];
        
        [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 事件上报: AD_Splash_show, w_scene=%@, w_revenue=%.2f", scene, ecpm];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] 事件上报异常: %@", exception.reason];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowSplashAdForScene:adId:)]) {
        [self.delegate dmAdManager:self didShowSplashAdForScene:scene adId:ad.adUnitIdentifier];
    }
}

- (void)didClickAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 👆 开屏广告被点击"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"💦 [MAX Splash]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    NSString *scene = [self getCurrentSplashScene];
    
    // 埋点：广告点击
    NSDictionary *clickParams = @{
        @"w_platform": @"MAX",
        @"w_ad_scene": scene,
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickAd:adType:)]) {
        [self.delegate dmAdManager:self didClickAd:ad.adUnitIdentifier adType:@"splash"];
    }
}

- (void)didHideAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 👻 开屏广告关闭"];
    
    NSString *scene = [self getCurrentSplashScene];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didCloseSplashAdForScene:adId:isUserClicked:)]) {
        [self.delegate dmAdManager:self didCloseSplashAdForScene:scene adId:ad.adUnitIdentifier isUserClicked:NO];
    }
    
    // 清理状态
    self.isSplashAdReady = NO;
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 开屏广告状态已重置"];
}

- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error
{
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] ❌ 开屏广告展示失败"];
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"💦 [MAX Splash] 错误代码: %ld", (long)error.code];
    
    NSString *scene = [self getCurrentSplashScene];
    
    // 埋点：展示失败
    NSDictionary *showFailParams = @{
        @"w_platform": @"MAX",
        @"w_ad_scene": scene,
        @"w_ad_type": @"splash",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_error_code": @(error.code),
        @"w_error_msg": error.message ?: @"展示失败"
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowSplashAdForScene:error:)]) {
        NSError *nsError = [NSError errorWithDomain:@"DualMediationMAXSplash" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"展示失败"}];
        [self.delegate dmAdManager:self didFailToShowSplashAdForScene:scene error:nsError];
    }
}

- (void)didPayRevenueForAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 开屏广告产生收益"];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 收益金额: $%.6f", ad.revenue];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 网络: %@", ad.networkName ?: @"unknown"];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 广告位: %@", ad.adUnitIdentifier ?: @"unknown"];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 广告格式: %@", ad.format ?: @"unknown"];
    [IMLogUtils info:IMLogTagAd format:@"💦 [MAX Splash] 💰 创意ID: %@", ad.creativeIdentifier ?: @"unknown"];
    
    // Firebase Analytics 收益跟踪
    NSDictionary *params = @{
        @"ad_platform": @"MAX",
        @"ad_source": ad.networkName ?: @"unknown",
        @"ad_unit_name": ad.adUnitIdentifier ?: @"unknown",
        @"ad_format": ad.format ?: @"splash",
        @"currency": @"USD",
        @"value": @(ad.revenue)
    };
    [IMLogUtils info:IMLogTagAd format:@"[MAX Splash] 上报 Firebase 收入事件: %@", params];
    [FIRAnalytics logEventWithName:@"ad_impression" parameters:params];
    [FIRAnalytics logEventWithName:@"Ad_Impression_Revenue" parameters:params];

    float previous = [[NSUserDefaults.standardUserDefaults valueForKey:@"TaichiTroasCache"] floatValue];
    float total = previous + ad.revenue;
    if (total >= 0.01) {
        [FIRAnalytics logEventWithName:@"Total_Ads_Revenue_001" parameters:@{
            kFIRParameterValue: @(total),
            kFIRParameterCurrency: @"USD"
        }];
        [[NSUserDefaults standardUserDefaults] setFloat:0 forKey:@"TaichiTroasCache"];
    } else {
        [[NSUserDefaults standardUserDefaults] setFloat:total forKey:@"TaichiTroasCache"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#endif

@end
